<?php
import('@.Org.BaseTool');
import('@.Org.CommonTool');
import('@.Org.UserTool');

/**
 * 获得购物车中的商品
 *
 * @access  public
 * @return  array
 */
function get_cart_goods(){	
	$CommonModel		=	new CommonModel();	
    /* 初始化 */
    $goods_list 		= 	array();
    $total 				= 	array(
        'goods_price'  => 0, // 本店售价合计（有格式）
        'market_price' => 0, // 市场售价合计（有格式）
        'saving'       => 0, // 节省金额（有格式）
        'save_rate'    => 0, // 节省百分比
        'goods_amount' => 0, // 本店售价合计（无格式）
    );

    /* 循环、统计 */
    $sql 				= 	"SELECT *, IF(parent_id, parent_id, goods_id) AS pid " .
				            " FROM " . 'ybr_cart' . " " .
				            " WHERE session_id = '" . SESS_ID . "' AND rec_type = '" . CART_GENERAL_GOODS . "'" .
				            " ORDER BY pid, parent_id";
    $res 				= 	$CommonModel->query($sql);

    /* 用于统计购物车中实体商品和虚拟商品的个数 */
    $virtual_goods_count 	= 	0;
    $real_goods_count    	= 	0;
	
    foreach($res as $row){
    	$total['goods_price']  	+= 	$row['goods_price'] * $row['goods_number'];
        $total['market_price']	+=	$row['market_price'] * $row['goods_number'];

        $row['subtotal']     	= 	price_format($row['goods_price'] * $row['goods_number'], false);
        $row['goods_price']  	= 	price_format($row['goods_price'], false);
        $row['market_price'] 	= 	price_format($row['market_price'], false);

        /* 统计实体商品和虚拟商品的个数 */
        if ($row['is_real']){
            $real_goods_count++;
        }
        else{
            $virtual_goods_count++;
        }

        /* 查询规格 */
        if (trim($row['goods_attr']) != ''){
            $sql 				= 	"SELECT attr_value FROM " . 'ybr_goods_attr' . " WHERE goods_attr_id " . db_create_in($row['goods_attr']);
            $attr_list 			= 	$CommonModel->getCol($sql);
            foreach ($attr_list AS $attr){
                $row['goods_name'] 	.= 	' [' . $attr . '] ';
            }
        }
        /* 增加是否在购物车里显示商品图 */
        if (($GLOBALS['_CFG']['show_goods_in_cart'] == "2" || $GLOBALS['_CFG']['show_goods_in_cart'] == "3") && $row['extension_code'] != 'package_buy'){
            $goods_thumb 		= 	$CommonModel->getOne("SELECT `goods_thumb` FROM " . 'ybr_goods' . " WHERE `goods_id`='{$row['goods_id']}'");
            $row['goods_thumb'] = 	get_image_path($row['goods_id'], $goods_thumb, true);
        }
        if ($row['extension_code'] == 'package_buy'){
            $row['package_goods_list'] 	= 	get_package_goods($row['goods_id']);
        }
        $goods_list[] 			= 	$row;
    }
    
    $total['goods_amount'] 		= 	$total['goods_price'];
    $total['saving']       		= 	price_format($total['market_price'] - $total['goods_price'], false);
    if ($total['market_price'] > 0){
        $total['save_rate'] 	= 	$total['market_price'] ? round(($total['market_price'] - $total['goods_price']) * 100 / $total['market_price']).'%' : 0;
    }
    $total['goods_price']  			= 	price_format($total['goods_price'], false);
    $total['market_price'] 			= 	price_format($total['market_price'], false);
    $total['real_goods_count']    	= 	$real_goods_count;
    $total['virtual_goods_count'] 	= 	$virtual_goods_count;

    return array('goods_list' => $goods_list, 'total' => $total);
}



/**
 * 获得指定礼包的商品
 *
 * @access  public
 * @param   integer $package_id
 * @return  array
 */
function get_package_goods($package_id){
	
    $sql 	= 	"SELECT pg.goods_id, g.goods_name, pg.goods_number, p.goods_attr, p.product_number, p.product_id
            	FROM " . 'ybr_package_goods' . " AS pg
                LEFT JOIN " .'ybr_goods' . " AS g ON pg.goods_id = g.goods_id
                LEFT JOIN " . 'ybr_products' . " AS p ON pg.product_id = p.product_id
            	WHERE pg.package_id = '$package_id'";
    if ($package_id == 0){
        $sql .= " AND pg.admin_id = '$_SESSION[admin_id]'";
    }
    $resource = M()->query($sql);
    if (!$resource){
        return array();
    }

    $row 				= 	array();
    $good_product_str 	= 	'';
	/* 生成结果数组 取存在货品的商品id 组合商品id与货品id */
    foreach($resource as $_row){
    	if ($_row['product_id'] > 0){
            /* 取存商品id */
            $good_product_str .= ',' . $_row['goods_id'];
            /* 组合商品id与货品id */
            $_row['g_p'] = $_row['goods_id'] . '_' . $_row['product_id'];
        }
        else{
            /* 组合商品id与货品id */
            $_row['g_p'] = $_row['goods_id'];
        }
        //生成结果数组
        $row[] = $_row;
    }
    
    $good_product_str 	= 	trim($good_product_str, ',');

    /* 释放空间 */
    unset($resource, $_row, $sql);

    /* 取商品属性 */
    if ($good_product_str != ''){
        $sql 				= 	"SELECT goods_attr_id, attr_value FROM " .'ybr_goods_attr'. " WHERE goods_id IN ($good_product_str)";
        $result_goods_attr 	= 	M()->query($sql);

        $_goods_attr = array();
        foreach ($result_goods_attr as $value){
            $_goods_attr[$value['goods_attr_id']] = $value['attr_value'];
        }
    }

    /* 过滤货品 */
    $format[0] 		= 	'%s[%s]--[%d]';
    $format[1] 		= 	'%s--[%d]';
    foreach ($row as $key => $value){
        if ($value['goods_attr'] != ''){
            $goods_attr_array 	= 	explode('|', $value['goods_attr']);

            $goods_attr 		= 	array();
            foreach ($goods_attr_array as $_attr){
                $goods_attr[] 	= 	$_goods_attr[$_attr];
            }
            $row[$key]['goods_name'] = sprintf($format[0], $value['goods_name'], implode('，', $goods_attr), $value['goods_number']);
        }
        else{
            $row[$key]['goods_name'] = sprintf($format[1], $value['goods_name'], $value['goods_number']);
        }
    }
    return $row;
}



/**
 *  获取指定用户的收藏商品列表
 *
 * @access  public
 * @param   int     $user_id        用户ID
 * @param   int     $num            列表最大数量
 * @param   int     $start          列表其实位置
 *
 * @return  array   $arr
 */
function get_collection_goods($user_id, $num = 10, $start = 0){
	
	$CommonModel	=	new CommonModel();
	
    $sql 			= 	'SELECT g.goods_id, g.goods_name, g.market_price, g.shop_price AS org_price, '.
                		"IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, ".
                		'g.promote_price, g.promote_start_date,g.promote_end_date, c.rec_id, c.is_attention' .
            			' FROM ' . 'ybr_collect_goods' . ' AS c' .
            			" LEFT JOIN " . 'ybr_goods' . " AS g ".
                		"ON g.goods_id = c.goods_id ".
            			" LEFT JOIN " . 'ybr_member_price' . " AS mp ".
                		"ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ".
            			" WHERE c.user_id = '$user_id' ORDER BY c.rec_id DESC";
    $res 			= 	$CommonModel->query($sql);

    $goods_list 	= 	array();
    
    foreach($res as $row){
    	if ($row['promote_price'] > 0){
            $promote_price 	= 	bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
        }
        else{
            $promote_price = 0;
        }
        $goods_list[$row['goods_id']]['rec_id']        = $row['rec_id'];
        $goods_list[$row['goods_id']]['is_attention']  = $row['is_attention'];
        $goods_list[$row['goods_id']]['goods_id']      = $row['goods_id'];
        $goods_list[$row['goods_id']]['goods_name']    = $row['goods_name'];
        $goods_list[$row['goods_id']]['market_price']  = price_format($row['market_price']);
        $goods_list[$row['goods_id']]['shop_price']    = price_format($row['shop_price']);
        $goods_list[$row['goods_id']]['promote_price'] = ($promote_price > 0) ? price_format($promote_price) : '';
        //$goods_list[$row['goods_id']]['url']           = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);
    }
    
    return $goods_list;
}


/**
 * 取得某用户等级当前时间可以享受的优惠活动
 * @param   int     $user_rank      用户等级id，0表示非会员
 * @return  array
 */
function favourable_list($user_rank){
	
	$CommonModel			=	new CommonModel();
	
    /* 购物车中已有的优惠活动及数量 */
    $used_list 				= 	cart_favourable();

    /* 当前用户可享受的优惠活动 */
    $favourable_list 		= 	array();
    $user_rank 				= 	',' . $user_rank . ',';
    $now 					= 	gmtime();
    $sql 					= 	"SELECT * " .
					            "FROM " . 'ybr_favourable_activity' .
					            " WHERE CONCAT(',', user_rank, ',') LIKE '%" . $user_rank . "%'" .
					            " AND start_time <= '$now' AND end_time >= '$now'" .
					            " AND act_type = '" . FAT_GOODS . "'" .
					            " ORDER BY sort_order";
    $res 					=	$CommonModel->query($sql);
        
    foreach($res as $favourable){
    	$favourable['start_time'] 				= 	local_date($GLOBALS['_CFG']['time_format'], $favourable['start_time']);
        $favourable['end_time']   				= 	local_date($GLOBALS['_CFG']['time_format'], $favourable['end_time']);
        $favourable['formated_min_amount']	 	= 	price_format($favourable['min_amount'], false);
        $favourable['formated_max_amount'] 		= 	price_format($favourable['max_amount'], false);
        $favourable['gift']       				= 	unserialize($favourable['gift']);

        foreach ($favourable['gift'] as $key => $value){
            $favourable['gift'][$key]['formated_price'] 	=	 price_format($value['price'], false);
            $sql 								= 	"SELECT COUNT(*) FROM " . 'ybr_goods' . " WHERE is_on_sale = 1 AND goods_id = ".$value['id'];
            $is_sale 							= 	$CommonModel->getOne($sql);
            if(!$is_sale){
                unset($favourable['gift'][$key]);
            }
        }

        $favourable['act_range_desc'] 			= 	act_range_desc($favourable);
        $favourable['act_type_desc'] = sprintf($GLOBALS['_LANG']['fat_ext'][$favourable['act_type']], $favourable['act_type_ext']);

        /* 是否能享受 */
        $favourable['available'] = favourable_available($favourable);
        if ($favourable['available'])
        {
            /* 是否尚未享受 */
            $favourable['available'] = !favourable_used($favourable, $used_list);
        }

        $favourable_list[] = $favourable;
    }
    return $favourable_list;
}

/**
 * 取得优惠范围描述
 * @param   array   $favourable     优惠活动
 * @return  string
 */
function act_range_desc($favourable){
	
	$CommonModel		=	new CommonModel();
	
    if ($favourable['act_range'] == FAR_BRAND){
        $sql 			= 	"SELECT brand_name FROM " . 'ybr_brand' . " WHERE brand_id " . db_create_in($favourable['act_range_ext']);
        return join(',', $CommonModel->getCol($sql));
    }
    elseif ($favourable['act_range'] == FAR_CATEGORY){
        $sql = "SELECT cat_name FROM " . 'ybr_category' . " WHERE cat_id " . db_create_in($favourable['act_range_ext']);
        return join(',', $CommonModel->getCol($sql));
    }
    elseif ($favourable['act_range'] == FAR_GOODS){
        $sql = "SELECT goods_name FROM " . 'ybr_goods' . " WHERE goods_id " . db_create_in($favourable['act_range_ext']);
        return join(',', $CommonModel->getCol($sql));
    }
    else{
        return '';
    }
}



/**
 * 计算折扣：根据购物车和优惠活动
 * @return  float   折扣
 */
function compute_discount(){
	
	$CommonModel	=	new CommonModel();
	
    /* 查询优惠活动 */
    $now 		= 	gmtime();
    $user_rank 	= 	',' . $_SESSION['user_rank'] . ',';
    $sql 		= 	"SELECT *" .
		            "FROM " . 'ybr_favourable_activity' .
		            " WHERE start_time <= '$now'" .
		            " AND end_time >= '$now'" .
		            " AND CONCAT(',', user_rank, ',') LIKE '%" . $user_rank . "%'" .
		            " AND act_type " . db_create_in(array(FAT_DISCOUNT, FAT_PRICE));
    $favourable_list 	= 	$CommonModel->query($sql);
    if (!$favourable_list){
        return 0;
    }

    /* 查询购物车商品 */
    $sql 		= 	"SELECT c.goods_id, c.goods_price * c.goods_number AS subtotal, g.cat_id, g.brand_id " .
		            "FROM " . 'ybr_cart' . " AS c, " . 'ybr_goods' . " AS g " .
		            "WHERE c.goods_id = g.goods_id " .
		            "AND c.session_id = '" . SESS_ID . "' " .
		            "AND c.parent_id = 0 " .
		            "AND c.is_gift = 0 " .
		            "AND rec_type = '" . CART_GENERAL_GOODS . "'";
    $goods_list = 	$CommonModel->query($sql);
    
    if (!$goods_list){
        return 0;
    }

    /* 初始化折扣 */
    $discount 			= 	0;
    $favourable_name 	= 	array();

    /* 循环计算每个优惠活动的折扣 */
    foreach ($favourable_list as $favourable){
        $total_amount 	= 	0;
        if ($favourable['act_range'] == FAR_ALL){
            foreach ($goods_list as $goods){
                $total_amount 	+= 	$goods['subtotal'];
            }
        }
        elseif ($favourable['act_range'] == FAR_CATEGORY){
            /* 找出分类id的子分类id */
            $id_list 		= 	array();
            $raw_id_list 	= 	explode(',', $favourable['act_range_ext']);
            foreach ($raw_id_list as $id){
                $id_list 	= 	array_merge($id_list, array_keys(cat_list($id, 0, false)));
            }
            $ids 			= 	join(',', array_unique($id_list));

            foreach ($goods_list as $goods){
                if (strpos(',' . $ids . ',', ',' . $goods['cat_id'] . ',') !== false){
                    $total_amount += $goods['subtotal'];
                }
            }
        }
        elseif ($favourable['act_range'] == FAR_BRAND){
            foreach ($goods_list as $goods){
                if (strpos(',' . $favourable['act_range_ext'] . ',', ',' . $goods['brand_id'] . ',') !== false){
                    $total_amount += $goods['subtotal'];
                }
            }
        }
        elseif ($favourable['act_range'] == FAR_GOODS){
            foreach ($goods_list as $goods){
                if (strpos(',' . $favourable['act_range_ext'] . ',', ',' . $goods['goods_id'] . ',') !== false){
                    $total_amount += $goods['subtotal'];
                }
            }
        }
        else{
            continue;
        }

        /* 如果金额满足条件，累计折扣 */
        if ($total_amount > 0 && $total_amount >= $favourable['min_amount'] && ($total_amount <= $favourable['max_amount'] || $favourable['max_amount'] == 0)){
            if ($favourable['act_type'] == FAT_DISCOUNT){
                $discount += $total_amount * (1 - $favourable['act_type_ext'] / 100);

                $favourable_name[] = $favourable['act_name'];
            }
            elseif ($favourable['act_type'] == FAT_PRICE){
                $discount += $favourable['act_type_ext'];

                $favourable_name[] = $favourable['act_name'];
            }
        }
    }

    return array('discount' => $discount, 'name' => $favourable_name);
}


/**
 * 取得购物车中已有的优惠活动及数量
 * @return  array
 */
function cart_favourable(){
    $list 		= 	array();
    $sql 		= 	"SELECT is_gift, COUNT(*) AS num " .
		            "FROM " . 'ybr_cart' .
		            " WHERE session_id = '" . SESS_ID . "'" .
		            " AND rec_type = '" . CART_GENERAL_GOODS . "'" .
		            " AND is_gift > 0" .
		            " GROUP BY is_gift";
    $res 		= 	M()->query($sql);
    
    foreach($res as $row){
    	$list[$row['is_gift']] = $row['num'];
    }    
    return $list;
}



/**
 * 删除购物车中的商品
 *
 * @access  public
 * @param   integer $id
 * @return  void
 */
function flow_drop_cart_goods($id){
	
	$CommonModel	=	new CommonModel();
	
    /* 取得商品id */
    $sql 			= 	"SELECT * FROM " . 'ybr_cart' . " WHERE rec_id = '$id'";
    $row 			= 	$CommonModel->getRow($sql);
    if ($row){
        //如果是超值礼包
        if ($row['extension_code'] == 'package_buy'){
            $sql 	= 	"DELETE FROM " . 'ybr_cart' .
                    	" WHERE session_id = '" . SESS_ID . "' " .
                    	"AND rec_id = '$id' LIMIT 1";
        }
        //如果是普通商品，同时删除所有赠品及其配件
        elseif ($row['parent_id'] == 0 && $row['is_gift'] == 0){
            /* 检查购物车中该普通商品的不可单独销售的配件并删除 */
            $sql 	= 	"SELECT c.rec_id
	                    FROM " . 'ybr_cart' . " AS c, " . 'ybr_group_goods' . " AS gg, " . 'ybr_goods' . " AS g
	                    WHERE gg.parent_id = '" . $row['goods_id'] . "'
	                    AND c.goods_id = gg.goods_id
	                    AND c.parent_id = '" . $row['goods_id'] . "'
	                    AND c.extension_code <> 'package_buy'
	                    AND gg.goods_id = g.goods_id
	                    AND g.is_alone_sale = 0";
            $res 		= 	$CommonModel->query($sql);
            $_del_str 	= 	$id . ',';
            
            foreach($res as $id_alone_sale_goods){
            	 $_del_str .= $id_alone_sale_goods['rec_id'] . ',';
            }
            
            $_del_str = trim($_del_str, ',');

            $sql 		= 	"DELETE FROM " . 'ybr_cart' .
		                    " WHERE session_id = '" . SESS_ID . "' " .
		                    "AND (rec_id IN ($_del_str) OR parent_id = '$row[goods_id]' OR is_gift <> 0)";
        }
        //如果不是普通商品，只删除该商品即可
        else{
            $sql 		= 	"DELETE FROM " . 'ybr_cart' .
		                    " WHERE session_id = '" . SESS_ID . "' " .
		                    "AND rec_id = '$id' LIMIT 1";
        }
        $CommonModel->query($sql);
    }

    flow_clear_cart_alone();
}


/**
 * 删除购物车中不能单独销售的商品
 *
 * @access  public
 * @return  void
 */
function flow_clear_cart_alone(){
	
	$CommonModel	=	new CommonModel();
	
    /* 查询：购物车中所有不可以单独销售的配件 */
    $sql 			= 	"SELECT c.rec_id, gg.parent_id
	            		FROM " . 'ybr_cart' . " AS c
		                LEFT JOIN " . 'ybr_group_goods' . " AS gg ON c.goods_id = gg.goods_id
		                LEFT JOIN" . 'ybr_goods' . " AS g ON c.goods_id = g.goods_id
			            WHERE c.session_id = '" . SESS_ID . "'
			            AND c.extension_code <> 'package_buy'
			            AND gg.parent_id > 0
			            AND g.is_alone_sale = 0";
    $res 			= 	$CommonModel->query($sql);
    $rec_id 		= 	array();
    foreach($res as $row){
    	$rec_id[$row['rec_id']][] = $row['parent_id'];
    }
    
    if (empty($rec_id)){
        return;
    }

    /* 查询：购物车中所有商品 */
    $sql 			= 	"SELECT DISTINCT goods_id
			            FROM " . 'ybr_cart' . "
			            WHERE session_id = '" . SESS_ID . "'
			            AND extension_code <> 'package_buy'";
    $res 			= 	$CommonModel->query($sql);
    $cart_good 		= 	array();
    
    foreach($res as $row){
    	$cart_good[] = $row['goods_id'];
    }
    
    if (empty($cart_good)){
        return;
    }

    /* 如果购物车中不可以单独销售配件的基本件不存在则删除该配件 */
    $del_rec_id = '';
    foreach ($rec_id as $key => $value){
        foreach ($value as $v){
            if (in_array($v, $cart_good)){
                continue 2;
            }
        }

        $del_rec_id = $key . ',';
    }
    $del_rec_id = trim($del_rec_id, ',');

    if ($del_rec_id == ''){
        return;
    }
    /* 删除 */
    $sql 		= 	"DELETE FROM " . ' ybr_cart ' ."
		            WHERE session_id = '" . SESS_ID . "'
		            AND rec_id IN ($del_rec_id)";
    $CommonModel->query($sql);
}


/**
 * 取得收货人信息
 * @param   int     $user_id    用户编号
 * @return  array
 */
function get_consignee($user_id){
	
	$CommonModel		=	new CommonModel();
	
    if ( isset($_SESSION['flow_consignee']) && !empty($_SESSION['flow_consignee']) ){
        /* 如果存在session，则直接返回session中的收货人信息 */
        return $_SESSION['flow_consignee'];
    }
    else{
        /* 如果不存在，则取得用户的默认收货人信息 */
        $arr 			= 	array();
        if ($user_id > 0){
            /* 取默认地址 */
            $sql 		= 	"SELECT ua.*".
		                    " FROM " . ' ybr_user_address ' . " AS ua, ".' ybr_users ' . ' AS u '.
		                    " WHERE u.user_id='$user_id' AND ua.address_id = u.address_id";
            $arr 		= 	$CommonModel->getRow($sql);
        }

        return $arr;
    }
}


/**
 * 检查收货人信息是否完整
 * @param   array   $consignee  收货人信息
 * @param   int     $flow_type  购物流程类型
 * @return  bool    true 完整 false 不完整
 */
function check_consignee_info($consignee, $flow_type){
    if (exist_real_goods(0, $flow_type)){    	
        /* 如果存在实体商品 */
        $res 		= 	!empty($consignee['consignee']) &&
			            !empty($consignee['country']) &&
			            //!empty($consignee['email']) && // 邮箱忽略
			            !empty($consignee['tel']);
			            
        if ($res){
            if (empty($consignee['province'])){
                /* 没有设置省份，检查当前国家下面有没有设置省份 */
                $pro 	= 	get_regions(1, $consignee['country']);
                $res 	= 	empty($pro);
            }
            elseif (empty($consignee['city'])){
                /* 没有设置城市，检查当前省下面有没有城市 */
                $city 	= 	get_regions(2, $consignee['province']);
                $res 	= 	empty($city);
            }
            elseif (empty($consignee['district'])){
                $dist = get_regions(3, $consignee['city']);
                $res = empty($dist);
            }
        }
        return $res;
    }
    else
    {
        /* 如果不存在实体商品 */
        return !empty($consignee['consignee']) &&
            !empty($consignee['email']) &&
            !empty($consignee['tel']);
    }
}

/**
 * 取得购物车商品
 * @param   int     $type   类型：默认普通商品
 * @return  array   购物车商品数组
 */
function cart_goods($type = CART_GENERAL_GOODS){
	
    $sql 			= 	"SELECT rec_id, user_id, goods_id, goods_name, goods_sn, goods_number, " .
			            "market_price, goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, is_shipping, " .
			            "goods_price * goods_number AS subtotal " .
			            "FROM " . 'ybr_cart' .
			            " WHERE session_id = '" . SESS_ID . "' " .
			            "AND rec_type = '$type'";
    $arr 			= 	M()->query($sql);

    /* 格式化价格及礼包商品 */
    foreach ($arr as $key => $value){
        $arr[$key]['formated_market_price'] 	= 	price_format($value['market_price'], false);
        $arr[$key]['formated_goods_price']  	= 	price_format($value['goods_price'], false);
        $arr[$key]['formated_subtotal']     	= 	price_format($value['subtotal'], false);

        if ($value['extension_code'] == 'package_buy'){
            $arr[$key]['package_goods_list'] 	= 	get_package_goods($value['goods_id']);
        }
    }
    return $arr;
}


/**
 * 获得订单信息
 *
 * @access  private
 * @return  array
 */
function flow_order_info(){
	
    $order 			= 	isset($_SESSION['flow_order']) ? $_SESSION['flow_order'] : array();

    /* 初始化配送和支付方式 */
    if (!isset($order['shipping_id']) || !isset($order['pay_id'])){
        /* 如果还没有设置配送和支付 */
        if ($_SESSION['user_id'] > 0){
            /* 用户已经登录了，则获得上次使用的配送和支付 */
            $arr 	= 	last_shipping_and_payment();

            if (!isset($order['shipping_id'])){
                $order['shipping_id'] = $arr['shipping_id'];
            }
            if (!isset($order['pay_id'])){
                $order['pay_id'] = $arr['pay_id'];
            }
        }
        else{
            if (!isset($order['shipping_id'])){
                $order['shipping_id'] = 0;
            }
            if (!isset($order['pay_id'])){
                $order['pay_id'] = 0;
            }
        }
    }

    if (!isset($order['pack_id'])){
        $order['pack_id'] = 0;  // 初始化包装
    }
    if (!isset($order['card_id'])){
        $order['card_id'] = 0;  // 初始化贺卡
    }
    if (!isset($order['bonus'])){
        $order['bonus'] = 0;    // 初始化红包
    }
    if (!isset($order['integral'])){
        $order['integral'] = 0; // 初始化积分
    }
    if (!isset($order['surplus'])){
        $order['surplus'] = 0;  // 初始化余额
    }

    /* 扩展信息 */
    if (isset($_SESSION['flow_type']) && intval($_SESSION['flow_type']) != CART_GENERAL_GOODS){
        $order['extension_code'] = $_SESSION['extension_code'];
        $order['extension_id'] = $_SESSION['extension_id'];
    }

    return $order;
}

/**
 * 获得上一次用户采用的支付和配送方式
 *
 * @access  public
 * @return  void
 */
function last_shipping_and_payment(){
	
	$CommonModel	=	new CommonModel();
	
    $sql 			= 	"SELECT shipping_id, pay_id " .
			            " FROM " . 'ybr_order_info' .
			            " WHERE user_id = '$_SESSION[user_id]' " .
			            " ORDER BY order_id DESC LIMIT 1";
    $row 			= 	$CommonModel->getRow($sql);

    if (empty($row)){
        /* 如果获得是一个空数组，则返回默认值 */
        $row 		= 	array('shipping_id' => 0, 'pay_id' => 0);
    }
    return $row;
}


/**
 * 获得订单中的费用信息
 *
 * @access  public
 * @param   array   $order
 * @param   array   $goods
 * @param   array   $consignee
 * @param   bool    $is_gb_deposit  是否团购保证金（如果是，应付款金额只计算商品总额和支付费用，可以获得的积分取 $gift_integral）
 * @return  array
 */
function order_fee($order, $goods, $consignee){
	
	$CommonModel		=	new CommonModel();
	
    /* 初始化订单的扩展code */
    if (!isset($order['extension_code'])){
        $order['extension_code'] 		= 	'';
    }

    if ($order['extension_code'] == 'group_buy'){
        $group_buy 						= 	group_buy_info($order['extension_id']);
    }

    $total  = array('real_goods_count' => 0,
                    'gift_amount'      => 0,
                    'goods_price'      => 0,
                    'market_price'     => 0,
                    'discount'         => 0,
                    'pack_fee'         => 0,
                    'card_fee'         => 0,
                    'shipping_fee'     => 0,
                    'shipping_insure'  => 0,
                    'integral_money'   => 0,
                    'bonus'            => 0,
                    'surplus'          => 0,
                    'cod_fee'          => 0,
                    'pay_fee'          => 0,
                    'tax'              => 0);
    $weight = 0;

    /* 商品总价 */
    foreach ($goods AS $val){
        /* 统计实体商品的个数 */
        if ($val['is_real']){
            $total['real_goods_count']++;
        }

        $total['goods_price']  	+= 	$val['goods_price'] * $val['goods_number'];
        $total['market_price'] 	+= 	$val['market_price'] * $val['goods_number'];
    }

    $total['saving']    			= 	$total['market_price'] - $total['goods_price'];
    $total['save_rate'] 			= 	$total['market_price'] ? round($total['saving'] * 100 / $total['market_price']) . '%' : 0;

    $total['goods_price_formated']  = 	price_format($total['goods_price'], false);
    $total['market_price_formated'] = 	price_format($total['market_price'], false);
    $total['saving_formated']       = 	price_format($total['saving'], false);

    /* 折扣 */
    if ($order['extension_code'] != 'group_buy'){
        $discount 					= 	compute_discount();
        $total['discount'] 			= 	$discount['discount'];
        if ($total['discount'] > $total['goods_price']){
            $total['discount'] 		= 	$total['goods_price'];
        }
    }
    $total['discount_formated'] 	= 	price_format($total['discount'], false);

    /* 税额 */
    if (!empty($order['need_inv']) && $order['inv_type'] != ''){
        /* 查税率 */
        $rate 						= 	0;
        foreach ($GLOBALS['_CFG']['invoice_type']['type'] as $key => $type){
            if ($type == $order['inv_type']){
                $rate 				= 	floatval($GLOBALS['_CFG']['invoice_type']['rate'][$key]) / 100;
                break;
            }
        }
        if ($rate > 0){
            $total['tax'] 			= 	$rate * $total['goods_price'];
        }
    }
    $total['tax_formated'] 			= 	price_format($total['tax'], false);

    /* 包装费用 */
    if (!empty($order['pack_id'])){
        $total['pack_fee']      	= 	pack_fee($order['pack_id'], $total['goods_price']);
    }
    $total['pack_fee_formated'] 	= 	price_format($total['pack_fee'], false);

    /* 贺卡费用 */
    if (!empty($order['card_id'])){
        $total['card_fee']      	= 	card_fee($order['card_id'], $total['goods_price']);
    }
    $total['card_fee_formated'] 	= 	price_format($total['card_fee'], false);

    /* 红包 */

    if (!empty($order['bonus_id'])){
        $bonus          			= 	bonus_info($order['bonus_id']);
        $total['bonus'] 			= 	$bonus['type_money'];
    }
    $total['bonus_formated'] 		= 	price_format($total['bonus'], false);

    /* 线下红包 */
     if (!empty($order['bonus_kill'])){
        $bonus          				= 	bonus_info(0,$order['bonus_kill']);
        $total['bonus_kill'] 			= 	$order['bonus_kill'];
        $total['bonus_kill_formated'] 	= 	price_format($total['bonus_kill'], false);
    }



    /* 配送费用 */
    $shipping_cod_fee 				= 	NULL;

    if ($order['shipping_id'] > 0 && $total['real_goods_count'] > 0){
        $region['country']  		= 	$consignee['country'];
        $region['province'] 		= 	$consignee['province'];
        $region['city']     		= 	$consignee['city'];
        $region['district'] 		=	$consignee['district'];
        $shipping_info 				= 	shipping_area_info($order['shipping_id'], $region);

        if (!empty($shipping_info)){
            if ($order['extension_code'] == 'group_buy'){
                $weight_price 		= 	cart_weight_price(CART_GROUP_BUY_GOODS);
            }
            else{
                $weight_price 		= 	cart_weight_price();
            }

            // 查看购物车中是否全为免运费商品，若是则把运费赋为零
            $sql 					= 	'SELECT count(*) FROM ' . 'ybr_cart' . " WHERE  `session_id` = '" . SESS_ID. "' AND `extension_code` != 'package_buy' AND `is_shipping` = 0";
            $shipping_count 		= 	$CommonModel->getOne($sql);

            $total['shipping_fee'] 	= 	($shipping_count == 0 AND $weight_price['free_shipping'] == 1) ?0 :  shipping_fee($shipping_info['shipping_code'],$shipping_info['configure'], $weight_price['weight'], $total['goods_price'], $weight_price['number']);

            if (!empty($order['need_insure']) && $shipping_info['insure'] > 0){
                $total['shipping_insure'] 	= 	shipping_insure_fee($shipping_info['shipping_code'],
                    $total['goods_price'], $shipping_info['insure']);
            }
            else{
                $total['shipping_insure'] 	= 	0;
            }

            if ($shipping_info['support_cod']){
                $shipping_cod_fee 			= 	$shipping_info['pay_fee'];
            }
        }
    }

    $total['shipping_fee_formated']    		= 	price_format($total['shipping_fee'], false);
    $total['shipping_insure_formated'] 		= 	price_format($total['shipping_insure'], false);

    // 购物车中的商品能享受红包支付的总额
    $bonus_amount 							= 	compute_discount_amount();
    // 红包和积分最多能支付的金额为商品总额
    $max_amount 							= 	$total['goods_price'] == 0 ? $total['goods_price'] : $total['goods_price'] - $bonus_amount;

    /* 计算订单总额 */
    if ($order['extension_code'] == 'group_buy' && $group_buy['deposit'] > 0){
        $total['amount'] 					= 	$total['goods_price'];
    }
    else{
        $total['amount'] 					= 	$total['goods_price'] - $total['discount'] + $total['tax'] + $total['pack_fee'] + $total['card_fee'] +	$total['shipping_fee'] + $total['shipping_insure'] + $total['cod_fee'];

        // 减去红包金额
        $use_bonus        					= 	min($total['bonus'], $max_amount); // 实际减去的红包金额
        if(isset($total['bonus_kill'])){
            $use_bonus_kill   				= 	min($total['bonus_kill'], $max_amount);
            $total['amount'] 				-=  $price = number_format($total['bonus_kill'], 2, '.', ''); // 还需要支付的订单金额
        }

        $total['bonus']   					= 	$use_bonus;
        $total['bonus_formated'] 	= 	price_format($total['bonus'], false);

        $total['amount'] 			-=	$use_bonus; // 还需要支付的订单金额
        $max_amount      			-= 	$use_bonus; // 积分最多还能支付的金额

    }

    /* 余额 */
    $order['surplus'] 				= 	$order['surplus'] > 0 ? $order['surplus'] : 0;
    if ($total['amount'] > 0){
        if (isset($order['surplus']) && $order['surplus'] > $total['amount']){
            $order['surplus'] 		= 	$total['amount'];
            $total['amount']  		= 	0;
        }
        else{
            $total['amount'] 		-= 	floatval($order['surplus']);
        }
    }
    else{
        $order['surplus'] 			= 	0;
        $total['amount']  			= 	0;
    }
    $total['surplus'] 				= 	$order['surplus'];
    $total['surplus_formated'] 		= 	price_format($order['surplus'], false);

    /* 积分 */
    $order['integral'] 				= 	$order['integral'] > 0 ? $order['integral'] : 0;
    if ($total['amount'] > 0 && $max_amount > 0 && $order['integral'] > 0){
        $integral_money 			= 	value_of_integral($order['integral']);

        // 使用积分支付
        $use_integral            	= 	min($total['amount'], $max_amount, $integral_money); // 实际使用积分支付的金额
        $total['amount']        	-=	$use_integral;
        $total['integral_money'] 	= 	$use_integral;
        $order['integral']       	= 	integral_of_value($use_integral);
    }
    else{
        $total['integral_money'] 	= 	0;
        $order['integral']       	= 	0;
    }
    $total['integral'] 				= 	$order['integral'];
    $total['integral_formated'] 	= 	price_format($total['integral_money'], false);

    /* 保存订单信息 */
    $_SESSION['flow_order'] 		= 	$order;

    $se_flow_type 					= 	isset($_SESSION['flow_type']) ? $_SESSION['flow_type'] : '';
    
    /* 支付费用 */
    if (!empty($order['pay_id']) && ($total['real_goods_count'] > 0 || $se_flow_type != CART_EXCHANGE_GOODS)){
        $total['pay_fee']      		= 	pay_fee($order['pay_id'], $total['amount'], $shipping_cod_fee);
    }

    $total['pay_fee_formated'] 		= 	price_format($total['pay_fee'], false);

    $total['amount']           		+= 	$total['pay_fee']; // 订单总额累加上支付费用
    $total['amount_formated']  		= 	price_format($total['amount'], false);

    /* 取得可以得到的积分和红包 */
    if ($order['extension_code'] == 'group_buy'){
        $total['will_get_integral'] 	= 	$group_buy['gift_integral'];
    }
    elseif ($order['extension_code'] == 'exchange_goods'){
        $total['will_get_integral'] 	= 	0;
    }
    else{
        $total['will_get_integral'] 	= 	get_give_integral($goods);
    }
    $total['will_get_bonus']        	= 	$order['extension_code'] == 'exchange_goods' ? 0 : price_format(get_total_bonus(), false);
    $total['formated_goods_price']  	= 	price_format($total['goods_price'], false);
    $total['formated_market_price'] 	= 	price_format($total['market_price'], false);
    $total['formated_saving']       	= 	price_format($total['saving'], false);

    if ($order['extension_code'] == 'exchange_goods'){
        $sql = 'SELECT SUM(eg.exchange_integral) '.
               'FROM ' . 'ybr_cart' . ' AS c,' . 'ybr_exchange_goods' . 'AS eg '.
               "WHERE c.goods_id = eg.goods_id AND c.session_id= '" . SESS_ID . "' " .
               "  AND c.rec_type = '" . CART_EXCHANGE_GOODS . "' " .
               '  AND c.is_gift = 0 AND c.goods_id > 0 ' .
               'GROUP BY eg.goods_id';
        $exchange_integral = $GLOBALS['db']->getOne($sql);
        $total['exchange_integral'] = $exchange_integral;
    }

    return $total;
}



/**
 * 取得团购活动信息
 * @param   int     $group_buy_id   团购活动id
 * @param   int     $current_num    本次购买数量（计算当前价时要加上的数量）
 * @return  array
 *                  status          状态：
 */
function group_buy_info($group_buy_id, $current_num = 0){
	$CommonModel		=	new CommonModel();
    /* 取得团购活动信息 */
    $group_buy_id = intval($group_buy_id);
    $sql = "SELECT *, act_id AS group_buy_id, act_desc AS group_buy_desc, start_time AS start_date, end_time AS end_date " .
            " FROM " . 'ybr_goods_activity' .
            " WHERE act_id = '$group_buy_id' " .
            " AND act_type = '" . GAT_GROUP_BUY . "'";
    //$group_buy = $GLOBALS['db']->getRow($sql);
    $group_buy	=	$CommonModel->getRow($sql);
    
    /* 如果为空，返回空数组 */
    if (empty($group_buy)){
        return array();
    }

    $ext_info 	= 	unserialize($group_buy['ext_info']);
    $group_buy	= 	array_merge($group_buy, $ext_info);
	
    /* 格式化时间 */
    $group_buy['formated_start_date'] 	= 	local_date('Y-m-d H:i', $group_buy['start_time']);
    $group_buy['formated_end_date'] 	= 	local_date('Y-m-d H:i', $group_buy['end_time']);

    /* 格式化保证金 */
    $group_buy['formated_deposit'] 		= 	price_format($group_buy['deposit'], false);

    /* 处理价格阶梯 */
    $price_ladder 						= 	$group_buy['price_ladder'];
    if (!is_array($price_ladder) || empty($price_ladder)){
        $price_ladder = array(array('amount' => 0, 'price' => 0));
    }
    else{
        foreach ($price_ladder as $key => $amount_price){
            $price_ladder[$key]['formated_price'] = price_format($amount_price['price'], false);
        }
    }
    $group_buy['price_ladder'] 	= 	$price_ladder;
    /* 统计信息 */
    $stat 						=	group_buy_stat($group_buy_id, $group_buy['deposit']);
    $group_buy 					= 	array_merge($group_buy, $stat);

    /* 计算当前价 */
    $cur_price  = $price_ladder[0]['price']; // 初始化
    $cur_amount = $stat['valid_goods'] + $current_num; // 当前数量
    foreach ($price_ladder as $amount_price)
    {
        if ($cur_amount >= $amount_price['amount'])
        {
            $cur_price = $amount_price['price'];
        }
        else
        {
            break;
        }
    }
    $group_buy['cur_price'] = $cur_price;
    $group_buy['formated_cur_price'] = price_format($cur_price, false);

    /* 最终价 */
    $group_buy['trans_price'] = $group_buy['cur_price'];
    $group_buy['formated_trans_price'] = $group_buy['formated_cur_price'];
    $group_buy['trans_amount'] = $group_buy['valid_goods'];

    /* 状态 */
    $group_buy['status'] = group_buy_status($group_buy);
    if (isset($GLOBALS['_LANG']['gbs'][$group_buy['status']]))
    {
        $group_buy['status_desc'] = $GLOBALS['_LANG']['gbs'][$group_buy['status']];
    }

    $group_buy['start_time'] = $group_buy['formated_start_date'];
    $group_buy['end_time'] = $group_buy['formated_end_date'];

    return $group_buy;
}


/**
 * 根据订单中的商品总额来获得包装的费用
 *
 * @access  public
 * @param   integer $pack_id
 * @param   float   $goods_amount
 * @return  float
 */
function pack_fee($pack_id, $goods_amount){
    $pack 		= 	pack_info($pack_id);
    $val 		= 	(floatval($pack['free_money']) <= $goods_amount && $pack['free_money'] > 0) ? 0 : floatval($pack['pack_fee']);
    return $val;
}

/**
 * 取得包装信息
 * @param   int     $pack_id    包装id
 * @return  array   包装信息
 */
function pack_info($pack_id){
	$CommonModel	=	new CommonModel();
    $sql 			= 	"SELECT * FROM " . 'ybr_pack' . " WHERE pack_id = '$pack_id'";
    return $CommonModel->getRow($sql);
}

/**
 * 根据订单中商品总额获得需要支付的贺卡费用
 *
 * @access  public
 * @param   integer $card_id
 * @param   float   $goods_amount
 * @return  float
 */
function card_fee($card_id, $goods_amount){
    $card 		= 	card_info($card_id);
    return ($card['free_money'] <= $goods_amount && $card['free_money'] > 0) ? 0 : $card['card_fee'];
}

/**
 * 取得贺卡信息
 * @param   int     $card_id    贺卡id
 * @return  array   贺卡信息
 */
function card_info($card_id){
    $CommonModel	=	new CommonModel();
	$sql 			= 	"SELECT * FROM " . 'ybr_card' . " WHERE card_id = '$card_id'";
    return $CommonModel->getRow($sql);
}

/**
 * 取得红包信息
 * @param   int     $bonus_id   红包id
 * @param   string  $bonus_sn   红包序列号
 * @param   array   红包信息
 */
function bonus_info($bonus_id, $bonus_sn = ''){
	$CommonModel	=	new CommonModel();
	
    $sql 			= 	"SELECT t.*, b.* " .
            			"FROM " . 'ybr_bonus_type' . " AS t," .
                		'ybr_user_bonus' . " AS b " .
            			"WHERE t.type_id = b.bonus_type_id ";
    if ($bonus_id > 0){
        $sql .= "AND b.bonus_id = '$bonus_id'";
    }
    else{
        $sql .= "AND b.bonus_sn = '$bonus_sn'";
    }
    return $CommonModel->getRow($sql);
}


/**
 * 取得某配送方式对应于某收货地址的区域信息
 * @param   int     $shipping_id        配送方式id
 * @param   array   $region_id_list     收货人地区id数组
 * @return  array   配送区域信息（config 对应着反序列化的 configure）
 */
function shipping_area_info($shipping_id, $region_id_list){
	$CommonModel	=	new CommonModel();
    $sql 			= 	'SELECT s.shipping_code, s.shipping_name, ' .
                		's.shipping_desc, s.insure, s.support_cod, a.configure ' .
            			'FROM ' . 'ybr_shipping' . ' AS s, ' .
                		'ybr_shipping_area' . ' AS a, ' .
                		'ybr_area_region' . ' AS r ' .
            			"WHERE s.shipping_id = '$shipping_id' " .
            			'AND r.region_id ' . db_create_in($region_id_list) .
            			' AND r.shipping_area_id = a.shipping_area_id AND a.shipping_id = s.shipping_id AND s.enabled = 1';
    $row = $CommonModel->getRow($sql);

    if (!empty($row)){
        $shipping_config = unserialize_config($row['configure']);
        if (isset($shipping_config['pay_fee'])){
            if (strpos($shipping_config['pay_fee'], '%') !== false){
                $row['pay_fee'] = floatval($shipping_config['pay_fee']) . '%';
            }
            else{
                 $row['pay_fee'] = floatval($shipping_config['pay_fee']);
            }
        }
        else{
            $row['pay_fee'] = 0.00;
        }
    }
    return $row;
}

/**
 * 获得购物车中商品的总重量、总价格、总数量
 *
 * @access  public
 * @param   int     $type   类型：默认普通商品
 * @return  array
 */
function cart_weight_price($type = CART_GENERAL_GOODS){
	
	$CommonModel					=	new CommonModel();
	
    $package_row['weight'] 			= 	0;
    $package_row['amount'] 			= 	0;
    $package_row['number'] 			= 	0;

    $packages_row['free_shipping'] 	= 	1;

    /* 计算超值礼包内商品的相关配送参数 */
    $sql 							= 	'SELECT goods_id, goods_number, goods_price FROM ' . 'ybr_cart' . " WHERE extension_code = 'package_buy' AND session_id = '" . SESS_ID . "'";
    $row 							= 	M()->query($sql);

    if ($row){
        $packages_row['free_shipping'] 	= 	0;
        $free_shipping_count 			= 	0;

        foreach ($row as $val){
            // 如果商品全为免运费商品，设置一个标识变量
            $sql 						= 	'SELECT count(*) FROM ' .
						                    'ybr_package_goods' . ' AS pg, ' .
						                    'ybr_goods' . ' AS g ' .
						                    "WHERE g.goods_id = pg.goods_id AND g.is_shipping = 0 AND pg.package_id = '"  . $val['goods_id'] . "'";
            $shipping_count 			= 	$CommonModel->getOne($sql);

            if ($shipping_count > 0){
                // 循环计算每个超值礼包商品的重量和数量，注意一个礼包中可能包换若干个同一商品
                $sql 					= 	'SELECT SUM(g.goods_weight * pg.goods_number) AS weight, ' .
						                    'SUM(pg.goods_number) AS number FROM ' .
						                    'ybr_package_goods' . ' AS pg, ' .
						                    'ybr_goods' . ' AS g ' .
						                    "WHERE g.goods_id = pg.goods_id AND g.is_shipping = 0 AND pg.package_id = '"  . $val['goods_id'] . "'";

                $goods_row 				= 	$CommonModel->getRow($sql);
                $package_row['weight'] 	+= 	floatval($goods_row['weight']) * $val['goods_number'];
                $package_row['amount']	+= 	floatval($val['goods_price']) * $val['goods_number'];
                $package_row['number'] 	+= 	intval($goods_row['number']) * $val['goods_number'];
            }
            else{
                $free_shipping_count++;
            }
        }

        $packages_row['free_shipping'] 	= 	$free_shipping_count == count($row) ? 1 : 0;
    }

    /* 获得购物车中非超值礼包商品的总重量 */
    $sql    							= 	'SELECT SUM(g.goods_weight * c.goods_number) AS weight, ' .
						                    'SUM(c.goods_price * c.goods_number) AS amount, ' .
						                    'SUM(c.goods_number) AS number '.
							                'FROM ' . 'ybr_cart' . ' AS c '.
							                'LEFT JOIN ' . 'ybr_goods' . ' AS g ON g.goods_id = c.goods_id '.
							                "WHERE c.session_id = '" . SESS_ID . "' " .
							                "AND rec_type = '$type' AND g.is_shipping = 0 AND c.extension_code != 'package_buy'";
    $row 								= 	$CommonModel->getRow($sql);

    $packages_row['weight'] 			= 	floatval($row['weight']) + $package_row['weight'];
    $packages_row['amount'] 			= 	floatval($row['amount']) + $package_row['amount'];
    $packages_row['number'] 			= 	intval($row['number']) + $package_row['number'];
    /* 格式化重量 */
    $packages_row['formated_weight'] 	= 	formated_weight($packages_row['weight']);

    return $packages_row;
}

/**
 * 计算运费
 * @param   string  $shipping_code      配送方式代码
 * @param   mix     $shipping_config    配送方式配置信息
 * @param   float   $goods_weight       商品重量
 * @param   float   $goods_amount       商品金额
 * @param   float   $goods_number       商品数量
 * @return  float   运费
 */
function shipping_fee($shipping_code, $shipping_config, $goods_weight, $goods_amount, $goods_number=''){
    if (!is_array($shipping_config)){
        $shipping_config = unserialize($shipping_config);
    }
    Vendor('Shipping.' . $shipping_code);
	if(class_exists($shipping_code)){
		$obj 	= 	new $shipping_code($shipping_config);
		return $obj->calculate($goods_weight, $goods_amount, $goods_number);
	}
	else{
		return 0;	
	}
}




/**
 * 获取指定配送的保价费用
 *
 * @access  public
 * @param   string      $shipping_code  配送方式的code
 * @param   float       $goods_amount   保价金额
 * @param   mix         $insure         保价比例
 * @return  float
 */
function shipping_insure_fee($shipping_code, $goods_amount, $insure){

    if (strpos($insure, '%') === false){
        /* 如果保价费用不是百分比则直接返回该数值 */
        return floatval($insure);
    }
    else{
    	// 导入shipping插件
		Vendor('Shipping.' . $shipping_code);
		
		if(class_exists($shipping_code)){			
			 $shipping 	= 	new $shipping_code;
			 $insure   	= 	floatval($insure) / 100;
			 
			if (method_exists($shipping, 'calculate_insure')){
                return $shipping->calculate_insure($goods_amount, $insure);
            }
            else{
                return ceil($goods_amount * $insure);
            }
		}
		else{
			 return false;
		}
    }
}

/**
 * 取得购物车该赠送的积分数
 * @return  int     积分数
 */
function get_give_integral(){	
	$CommonModel	=	new CommonModel();
	
	$sql 			= 	"SELECT SUM(c.goods_number * IF(g.give_integral > -1, g.give_integral, c.goods_price))" .
						"FROM " . 'ybr_cart' . " AS c, " .
						'ybr_goods' . " AS g " .
						"WHERE c.goods_id = g.goods_id " .
						"AND c.session_id = '" . SESS_ID . "' " .
						"AND c.goods_id > 0 " .
						"AND c.parent_id = 0 " .
						"AND c.rec_type = 0 " .
						"AND c.is_gift = 0";
	return intval($CommonModel->getOne($sql));
}

/**
 * 处理序列化的支付、配送的配置参数
 * 返回一个以name为索引的数组
 *
 * @access  public
 * @param   string       $cfg
 * @return  void
 */
function unserialize_config($cfg){
    if (is_string($cfg) && ($arr = unserialize($cfg)) !== false){
        $config = array();
        foreach ($arr AS $key => $val){
            $config[$val['name']] = $val['value'];
        }
        return $config;
    }
    else{
        return false;
    }
}

/**
 * 格式化重量：小于1千克用克表示，否则用千克表示
 * @param   float   $weight     重量
 * @return  string  格式化后的重量
 */
function formated_weight($weight){
    $weight = round(floatval($weight), 3);
    if ($weight > 0){
        if ($weight < 1){
            /* 小于1千克，用克表示 */
            return intval($weight * 1000) . L('gram');
        }
        else{
            /* 大于1千克，用千克表示 */
            return $weight . L('kilogram');
        }
    }
    else{
        return 0;
    }
}



/**
 * 计算购物车中的商品能享受红包支付的总额
 * @return  float   享受红包支付的总额
 */
function compute_discount_amount(){
	
	$CommonModel	=	new CommonModel();
	
    /* 查询优惠活动 */
    $now 			= 	gmtime();
    $user_rank 		= 	',' . $_SESSION['user_rank'] . ',';
    $sql 			= 	"SELECT *" .
			            "FROM " . 'ybr_favourable_activity' .
			            " WHERE start_time <= '$now'" .
			            " AND end_time >= '$now'" .
			            " AND CONCAT(',', user_rank, ',') LIKE '%" . $user_rank . "%'" .
			            " AND act_type " . db_create_in(array(FAT_DISCOUNT, FAT_PRICE));
    $favourable_list 	= 	$CommonModel->query($sql);
    if (!$favourable_list){
        return 0;
    }

    /* 查询购物车商品 */
    $sql 			= 	"SELECT c.goods_id, c.goods_price * c.goods_number AS subtotal, g.cat_id, g.brand_id " .
			            "FROM " . 'ybr_cart' . " AS c, " . 'ybr_goods' . " AS g " .
			            "WHERE c.goods_id = g.goods_id " .
			            "AND c.session_id = '" . SESS_ID . "' " .
			            "AND c.parent_id = 0 " .
			            "AND c.is_gift = 0 " .
			            "AND rec_type = '" . CART_GENERAL_GOODS . "'";
    $goods_list 	= 	$CommonModel->query($sql);
    if (!$goods_list){
        return 0;
    }

    /* 初始化折扣 */
    $discount 			= 	0;
    $favourable_name 	= 	array();

    /* 循环计算每个优惠活动的折扣 */
    foreach ($favourable_list as $favourable){
        $total_amount = 0;
        if ($favourable['act_range'] == FAR_ALL){
            foreach ($goods_list as $goods){
                $total_amount += $goods['subtotal'];
            }
        }
        elseif ($favourable['act_range'] == FAR_CATEGORY){
            /* 找出分类id的子分类id */
            $id_list 		= 	array();
            $raw_id_list 	= 	explode(',', $favourable['act_range_ext']);
            foreach ($raw_id_list as $id){
                $id_list 	= 	array_merge($id_list, array_keys(cat_list($id, 0, false)));
            }
            $ids 			= 	join(',', array_unique($id_list));

            foreach ($goods_list as $goods){
                if (strpos(',' . $ids . ',', ',' . $goods['cat_id'] . ',') !== false){
                    $total_amount 	+= 	$goods['subtotal'];
                }
            }
        }
        elseif ($favourable['act_range'] == FAR_BRAND){
            foreach ($goods_list as $goods){
                if (strpos(',' . $favourable['act_range_ext'] . ',', ',' . $goods['brand_id'] . ',') !== false){
                    $total_amount 	+= 	$goods['subtotal'];
                }
            }
        }
        elseif ($favourable['act_range'] == FAR_GOODS){
            foreach ($goods_list as $goods){
                if (strpos(',' . $favourable['act_range_ext'] . ',', ',' . $goods['goods_id'] . ',') !== false){
                    $total_amount 	+= 	$goods['subtotal'];
                }
            }
        }
        else{
            continue;
        }
        if ($total_amount > 0 && $total_amount >= $favourable['min_amount'] && ($total_amount <= $favourable['max_amount'] || $favourable['max_amount'] == 0)){
            if ($favourable['act_type'] == FAT_DISCOUNT){
                $discount 			+= 	$total_amount * (1 - $favourable['act_type_ext'] / 100);
            }
            elseif ($favourable['act_type'] == FAT_PRICE){
                $discount 			+= 	$favourable['act_type_ext'];
            }
        }
    }    
    return $discount;
}

/**
 * 获得订单需要支付的支付费用
 *
 * @access  public
 * @param   integer $payment_id
 * @param   float   $order_amount
 * @param   mix     $cod_fee
 * @return  float
 */
function pay_fee($payment_id, $order_amount, $cod_fee=null){
    $pay_fee 	= 	0;
    $payment 	= 	payment_info($payment_id);
    $rate    	= 	($payment['is_cod'] && !is_null($cod_fee)) ? $cod_fee : $payment['pay_fee'];

    if (strpos($rate, '%') !== false){
        /* 支付费用是一个比例 */
        $val     = floatval($rate) / 100;
        $pay_fee = $val > 0 ? $order_amount * $val /(1- $val) : 0;
    }
    else{
        $pay_fee = floatval($rate);
    }
    return round($pay_fee, 2);
}

/**
 * 取得支付方式信息
 * @param   int     $pay_id     支付方式id
 * @return  array   支付方式信息
 */
function payment_info($pay_id){
    $sql 	= 	'SELECT * FROM ' . 'ybr_payment' .
	            " WHERE pay_id = '$pay_id' AND enabled = 1";
	$datas	=	M()->query($sql);
    return empty($datas) ? array(): $datas[0];
}



/**
 * 取得当前用户应该得到的红包总额
 */
function get_total_bonus(){
	
	$CommonModel	=	new CommonModel();
	
    $day    		= 	getdate();
    $today  		= 	local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);

    /* 按商品发的红包 */
    $sql 			= 	"SELECT SUM(c.goods_number * t.type_money)" .
            			"FROM " . 'ybr_cart' . " AS c, "
	                    . 'ybr_bonus_type' . " AS t, "
	                    . 'ybr_goods' . " AS g " .
			            "WHERE c.session_id = '" . SESS_ID . "' " .
			            "AND c.is_gift = 0 " .
			            "AND c.goods_id = g.goods_id " .
			            "AND g.bonus_type_id = t.type_id " .
			            "AND t.send_type = '" . SEND_BY_GOODS . "' " .
			            "AND t.send_start_date <= '$today' " .
			            "AND t.send_end_date >= '$today' " .
			            "AND c.rec_type = '" . CART_GENERAL_GOODS . "'";
    $goods_total 	= 	floatval($CommonModel->getOne($sql));

    /* 取得购物车中非赠品总金额 */
    $sql 			= 	"SELECT SUM(goods_price * goods_number) " .
			            "FROM " . 'ybr_cart' .
			            " WHERE session_id = '" . SESS_ID . "' " .
			            " AND is_gift = 0 " .
			            " AND rec_type = '" . CART_GENERAL_GOODS . "'";
    $amount 		= 	floatval($CommonModel->getOne($sql));

    /* 按订单发的红包 */
    $sql 			= 	"SELECT FLOOR('$amount' / min_amount) * type_money " .
			            "FROM " . 'ybr_bonus_type' .
			            " WHERE send_type = '" . SEND_BY_ORDER . "' " .
			            " AND send_start_date <= '$today' " .
			            "AND send_end_date >= '$today' " .
			            "AND min_amount > 0 ";
    $order_total 	= 	floatval($CommonModel->getOne($sql));

    return $goods_total + $order_total;
}

/**
 * 取得可用的配送方式列表
 * @param   array   $region_id_list     收货人地区id数组（包括国家、省、市、区）
 * @return  array   配送方式数组
 */
function available_shipping_list($region_id_list){
    $sql 	= 	'SELECT s.shipping_id, s.shipping_code, s.shipping_name, ' .
                's.shipping_desc, s.insure, s.support_cod, a.configure ' .
            	'FROM ' . 'ybr_shipping' . ' AS s, ' .
                'ybr_shipping_area' . ' AS a, ' .
                'ybr_area_region' . ' AS r ' .
            	'WHERE r.region_id ' . db_create_in($region_id_list) .
            	' AND r.shipping_area_id = a.shipping_area_id AND a.shipping_id = s.shipping_id AND s.enabled = 1 ORDER BY s.shipping_order';
	return M()->query($sql);
}

/**
 * 取得配送方式信息
 * @param   int     $shipping_id    配送方式id
 * @return  array   配送方式信息
 */
function shipping_info($shipping_id){
	$CommonModel	=	new CommonModel();
    $sql 			= 	'SELECT * FROM ' . 'ybr_shipping' .
            			" WHERE shipping_id = '$shipping_id' " .
            			'AND enabled = 1';
    return $CommonModel->getRow($sql);
}

/**
 * 取得可用的支付方式列表
 * @param   bool    $support_cod        配送方式是否支持货到付款
 * @param   int     $cod_fee            货到付款手续费（当配送方式支持货到付款时才传此参数）
 * @param   int     $is_online          是否支持在线支付
 * @return  array   配送方式数组
 */
function available_payment_list($support_cod, $cod_fee = 0, $is_online = false){
    $sql 		= 	'SELECT pay_id, pay_code, pay_name, pay_fee, pay_desc, pay_config, is_cod' .
		            ' FROM ' . 'ybr_payment' .
		            ' WHERE enabled = 1 ';
    if (!$support_cod){
        $sql 	.= 	'AND is_cod = 0 '; // 如果不支持货到付款
    }
    if ($is_online){
        $sql 	.= 	"AND is_online = '1' ";
    }
    $sql 		.= 	'ORDER BY pay_order'; // 排序
    $res 		= 	M()->query($sql);
    
    $pay_list 	= 	array();
    foreach($res as $row) {
    	 if ($row['is_cod'] == '1'){
            $row['pay_fee'] 	= 	$cod_fee;
        }
        $row['format_pay_fee'] 	= 	strpos($row['pay_fee'], '%') !== false ? $row['pay_fee'] :
        price_format($row['pay_fee'], false);
        $modules[] 				=	$row;
    }   
    //include_once(ROOT_PATH.'includes/lib_compositor.php');
    import("@.Pay.Compositor");
    
    if(isset($modules)){
        return $modules;
    }
}

/**
 * 取得包装列表
 * @return  array   包装列表
 */
function pack_list(){
    $sql 		= 	'SELECT * FROM ' . 'ybr_pack';
    $res 		= 	M()->query($sql);

    $list 		= 	array();
    foreach($res as $row){
    	$row['format_pack_fee'] 	= 	price_format($row['pack_fee'], false);
        $row['format_free_money'] 	= 	price_format($row['free_money'], false);
        $list[] 					=	$row;
    }
    return $list;
}

/**
 * 取得贺卡列表
 * @return  array   贺卡列表
 */
function card_list(){
    $sql = "SELECT * FROM " . 'ybr_card';
    $res = M()->query($sql);

    $list = array();
    foreach($res as $row){
    	$row['format_card_fee'] = price_format($row['card_fee'], false);
        $row['format_free_money'] = price_format($row['free_money'], false);
        $list[] = $row;
    }
    return $list;
}

/**
 * 取得用户当前可用红包
 * @param   int     $user_id        用户id
 * @param   float   $goods_amount   订单商品金额
 * @return  array   红包数组
 */
function user_bonus($user_id, $goods_amount = 0){
    $day    = 	getdate();
    $today  = 	local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);

    $sql	= 	"SELECT t.type_id, t.type_name, t.type_money, b.bonus_id " .
            	"FROM " . 'ybr_bonus_type' . " AS t," .
                'ybr_user_bonus' . " AS b " .
            	"WHERE t.type_id = b.bonus_type_id " .
            	"AND t.use_start_date <= '$today' " .
            	"AND t.use_end_date >= '$today' " .
            	"AND t.min_goods_amount <= '$goods_amount' " .
            	"AND b.user_id<>0 " .
            	"AND b.user_id = '$user_id' " .
            	"AND b.order_id = 0";
    return M()->query($sql);
}


/**
 * 检查订单中商品库存
 *
 * @access  public
 * @param   array   $arr
 *
 * @return  void
 */
function flow_cart_stock($arr){
	
	$CommonModel		=	new CommonModel();
	
    foreach ($arr AS $key => $val){
        $val 			= 	intval(make_semiangle($val));
        
        if ($val <= 0 || !is_numeric($key)){
            continue;
        }

        $sql 			= 	"SELECT `goods_id`, `goods_attr_id`, `extension_code` FROM" . 'ybr_cart' .
               				" WHERE rec_id='$key' AND session_id='" . SESS_ID . "'";
        $goods 			= 	$CommonModel->getRow($sql);

        $sql 			= 	"SELECT g.goods_name, g.goods_number, c.product_id ".
                			"FROM " .'ybr_goods' . " AS g, ".
                    		'ybr_cart' . " AS c ".
                			"WHERE g.goods_id = c.goods_id AND c.rec_id = '$key'";
        $row 			= 	$CommonModel->getRow($sql);

        //系统启用了库存，检查输入的商品数量是否有效
        if (intval($GLOBALS['_CFG']['use_storage']) > 0 && $goods['extension_code'] != 'package_buy'){
        	
            if ($row['goods_number'] < $val){
                $this->error( sprintf($GLOBALS['_LANG']['stock_insufficiency'], $row['goods_name'], $row['goods_number'], $row['goods_number']) );
            }

            /* 是货品 */
            $row['product_id'] 		= 	trim($row['product_id']);
            if (!empty($row['product_id'])){
                $sql 				= 	"SELECT product_number FROM " .'ybr_products' . " WHERE goods_id = '" . $goods['goods_id'] . "' AND product_id = '" . $row['product_id'] . "'";
                $product_number 	= 	$CommonModel->getOne($sql);
                if ($product_number < $val){
                    $this->error( sprintf($GLOBALS['_LANG']['stock_insufficiency'], $row['goods_name'], $row['goods_number'], $row['goods_number']) );
                }
            }
        }
        elseif (intval($GLOBALS['_CFG']['use_storage']) > 0 && $goods['extension_code'] == 'package_buy'){
            if (judge_package_stock($goods['goods_id'], $val)){
                show_message($GLOBALS['_LANG']['package_stock_insufficiency']);
                exit;
            }
        }
    }

}



/**
 * 检查礼包内商品的库存
 * @return  boolen
 */
function judge_package_stock($package_id, $package_num = 1){
    $sql 		= 	"SELECT goods_id, product_id, goods_number
		            FROM " . 'ybr_package_goods' . "
		            WHERE package_id = '" . $package_id . "'";
    $row 		= 	M()->query($sql);
    if (empty($row)){
        return true;
    }

    /* 分离货品与商品 */
    $goods 		= 	array('product_ids' => '', 'goods_ids' => '');
    foreach ($row as $value){
        if ($value['product_id'] > 0){
            $goods['product_ids'] 	.= 	',' . $value['product_id'];
            continue;
        }
        $goods['goods_ids'] 		.= 	',' . $value['goods_id'];
    }

    /* 检查货品库存 */
    if ($goods['product_ids'] != ''){
        $sql 	= 	"SELECT p.product_id
	                FROM " . 'ybr_products' . " AS p, " . 'ybr_package_goods' . " AS pg
	                WHERE pg.product_id = p.product_id
	                AND pg.package_id = '$package_id'
	                AND pg.goods_number * $package_num > p.product_number
	                AND p.product_id IN (" . trim($goods['product_ids'], ',') . ")";
        $row 	= 	M()->query($sql);

        if (!empty($row)){
            return true;
        }
    }

    /* 检查商品库存 */
    if ($goods['goods_ids'] != ''){
        $sql 	= 	"SELECT g.goods_id
	                FROM " . 'ybr_goods'  . "AS g, " . 'ybr_package_goods' . " AS pg
	                WHERE pg.goods_id = g.goods_id
	                AND pg.goods_number * $package_num > g.goods_number
	                AND pg.package_id = '" . $package_id . "'
	                AND pg.goods_id IN (" . trim($goods['goods_ids'], ',') . ")";
        $row 	= 	M()->query($sql);

        if (!empty($row)){
            return true;
        }
    }
    return false;
}

/**
 * 查询配送区域属于哪个办事处管辖
 * @param   array   $regions    配送区域（1、2、3、4级按顺序）
 * @return  int     办事处id，可能为0
 */
function get_agency_by_regions($regions){
    if (!is_array($regions) || empty($regions)){
        return 0;
    }

    $arr 	= 	array();
    $sql 	= 	"SELECT region_id, agency_id " .
            	"FROM " . 'ybr_region' .
            	" WHERE region_id " . db_create_in($regions) .
            	" AND region_id > 0 AND agency_id > 0";
    $res 	= 	M()->query($sql);
    
    foreach($res as $row){
    	$arr[$row['region_id']] = $row['agency_id'];
    }

    if (empty($arr)){
        return 0;
    }

    $agency_id = 0;
    for ($i = count($regions) - 1; $i >= 0; $i--){
        if (isset($arr[$regions[$i]])){
            return $arr[$regions[$i]];
        }
    }
}


/**
 * 获得用户的可用积分
 *
 * @access  private
 * @return  integral
 */
function flow_available_points(){
	
	$ComonModel	=	new CommonModel();
	
    $sql 		= 	"SELECT SUM(g.integral * c.goods_number) ".
		            "FROM " . 'ybr_cart' . " AS c, " . 'ybr_goods' . " AS g " .
		            "WHERE c.session_id = '" . SESS_ID . "' AND c.goods_id = g.goods_id AND c.is_gift = 0 AND g.integral > 0 " .
		            "AND c.rec_type = '" . CART_GENERAL_GOODS . "'";

    $val 		= 	intval($ComonModel->getOne($sql));

    return integral_of_value($val);
}

/**
 * 计算指定的金额需要多少积分
 *
 * @access  public
 * @param   integer $value  金额
 * @return  void
 */
function integral_of_value($value){
    $scale 	= 	floatval($GLOBALS['_CFG']['integral_scale']);
    return $scale > 0 ? round($value / $scale * 100) : 0;
}

/**
 * 得到新订单号
 * @return  string
 */
function get_order_sn(){
    /* 选择一个随机的方案 */
    mt_srand((double) microtime() * 1000000);    
    //return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    return date('ymd') . substr(time(),-4) . substr(microtime(),3,6) . sprintf('%02d', rand(0, 99)); // 并发量 1/1000000
}

/**
 *  虚拟商品发货
 *
 * @access  public
 * @param   array  $virtual_goods   虚拟商品数组
 * @param   string $msg             错误信息
 * @param   string $order_sn        订单号。
 * @param   string $process         设定当前流程：split，发货分单流程；other，其他，默认。
 *
 * @return bool
 */
function virtual_goods_ship(&$virtual_goods, &$msg, $order_sn, $return_result = false, $process = 'other'){
    $virtual_card 			= 	array();
    foreach ($virtual_goods AS $code => $goods_list){
        /* 只处理虚拟卡 */
        if ($code == 'virtual_card'){
            foreach ($goods_list as $goods){
                if (virtual_card_shipping($goods, $order_sn, $msg, $process)){
                    if ($return_result){
                        $virtual_card[] 	= 	array('goods_id'=>$goods['goods_id'], 'goods_name'=>$goods['goods_name'], 'info'=>virtual_card_result($order_sn, $goods));
                    }
                }
                else{
                    return false;
                }
            }
            $GLOBALS['smarty']->assign('virtual_card',      $virtual_card);
        }
    }
    return true;
}

/**
 *  虚拟卡发货
 *
 * @access  public
 * @param   string      $goods      商品详情数组
 * @param   string      $order_sn   本次操作的订单
 * @param   string      $msg        返回信息
 * @param   string      $process    设定当前流程：split，发货分单流程；other，其他，默认。
 *
 * @return  boolen
 */
function virtual_card_shipping ($goods, $order_sn, &$msg, $process = 'other'){
    /* 包含加密解密函数所在文件 */
    //include_once(ROOT_PATH . 'includes/lib_code.php');
    $CommonModel	=	new CommonModel();

    /* 检查有没有缺货 */
    $sql 			= 	"SELECT COUNT(*) FROM ".'ybr_virtual_card' . " WHERE goods_id = '$goods[goods_id]' AND is_saled = 0 ";
    $num 			= 	$CommonModel->GetOne($sql);

    if ($num < $goods['num']){
        $msg 		.= 	sprintf(L('virtual_card_oos'), $goods['goods_name']);
        return false;
    }

     /* 取出卡片信息 */
     $sql 			= 	"SELECT card_id, card_sn, card_password, end_date, crc32 FROM ".'ybr_virtual_card' . " WHERE goods_id = '$goods[goods_id]' AND is_saled = 0  LIMIT " . $goods['num'];
     $arr 			= 	$CommonModel->query($sql);

     $card_ids 		= 	array();
     $cards 		= 	array();

     foreach ($arr as $virtual_card){
        $card_info = array();

        /* 卡号和密码解密 */
        if ($virtual_card['crc32'] == 0 || $virtual_card['crc32'] == crc32(AUTH_KEY)){
            $card_info['card_sn'] = decrypt($virtual_card['card_sn']);
            $card_info['card_password'] = decrypt($virtual_card['card_password']);
        }
        elseif ($virtual_card['crc32'] == crc32(OLD_AUTH_KEY)){
            $card_info['card_sn'] = decrypt($virtual_card['card_sn'], OLD_AUTH_KEY);
            $card_info['card_password'] = decrypt($virtual_card['card_password'], OLD_AUTH_KEY);
        }
        else{
            $msg .= 'error key';

            return false;
        }
        $card_info['end_date'] 	= 	date("Y-m-d H:i:s", $virtual_card['end_date']);
        $card_ids[] 			= 	$virtual_card['card_id'];
        $cards[] 				= 	$card_info;
     }

     /* 标记已经取出的卡片 */
    $sql = "UPDATE " . ' ybr_virtual_card ' . " SET " . "is_saled = 1 ," . "order_sn = '$order_sn' " . "WHERE " . db_create_in($card_ids, 'card_id');
    if (!$CommonModel->query($sql)){
        $msg .= $CommonModel->getError();
        return false;
    }

    /* 更新库存 */
    $sql = "UPDATE ".'ybr_goods'. " SET goods_number = goods_number - '$goods[num]' WHERE goods_id = '$goods[goods_id]'";
    M()->query($sql);

    if (true){
        /* 获取订单信息 */
        $sql = "SELECT order_id, order_sn, consignee, email FROM ".'ybr_order_info' . " WHERE order_sn = '$order_sn'";
        $order = $CommonModel->GetRow($sql);

        /* 更新订单信息 */
        if ($process == 'split'){
            $sql = "UPDATE ".'ybr_order_goods'. "
                    SET send_number = send_number + '" . $goods['num'] . "'
                    WHERE order_id = '" . $order['order_id'] . "'
                    AND goods_id = '" . $goods['goods_id'] . "' ";
        }
        else{
            $sql = "UPDATE ".'ybr_order_goods'. "
                    SET send_number = '" . $goods['num'] . "'
                    WHERE order_id = '" . $order['order_id'] . "'
                    AND goods_id = '" . $goods['goods_id'] . "' ";
        }

        if (!$CommonModel->query($sql, 'SILENT')){
            $msg .= $CommonModel->getError();
            return false;
        }
    }

//    /* 发送邮件 */
//    $GLOBALS['smarty']->assign('virtual_card',                   $cards);
//    $GLOBALS['smarty']->assign('order',                          $order);
//    $GLOBALS['smarty']->assign('goods',                          $goods);
//
//    $GLOBALS['smarty']->assign('send_time', date('Y-m-d H:i:s'));
//    $GLOBALS['smarty']->assign('shop_name', $GLOBALS['_CFG']['shop_name']);
//    $GLOBALS['smarty']->assign('send_date', date('Y-m-d'));
//    $GLOBALS['smarty']->assign('sent_date', date('Y-m-d'));
//
//    $tpl = get_mail_template('virtual_card');
//    $content = $GLOBALS['smarty']->fetch('str:' . $tpl['template_content']);
//    send_mail($order['consignee'], $order['email'], $tpl['template_subject'], $content, $tpl['is_html']);

    return true;
}


/**
 *  返回虚拟卡信息
 *
 * @access  public
 * @param
 *
 * @return void
 */
function virtual_card_result($order_sn, $goods){
    /* 包含加密解密函数所在文件 */
    import('@.Org.Encryption');

    /* 获取已经发送的卡片数据 */
    $sql 			= 	"SELECT card_sn, card_password, end_date, crc32 FROM " . 'ybr_virtual_card' . " WHERE goods_id= '$goods[goods_id]' AND order_sn = '$order_sn' ";
    $res			= 	M()->query($sql);

    $cards 			= 	array();

    foreach($res as $row){
    	 /* 卡号和密码解密 */
        if ($row['crc32'] == 0 || $row['crc32'] == crc32(AUTH_KEY)){
            $row['card_sn'] 			= 	decrypt($row['card_sn']);
            $row['card_password'] 		= 	decrypt($row['card_password']);
        }
        elseif ($row['crc32'] == crc32(OLD_AUTH_KEY)){
            $row['card_sn'] 			= 	decrypt($row['card_sn'], OLD_AUTH_KEY);
            $row['card_password'] 		= 	decrypt($row['card_password'], OLD_AUTH_KEY);
        }
        else{
            $row['card_sn'] = '***';
            $row['card_password'] = '***';
        }

        $cards[] 						= 	array('card_sn'=>$row['card_sn'], 'card_password'=>$row['card_password'], 'end_date'=>date($GLOBALS['_CFG']['date_format'], $row['end_date']));
    }
    return $cards;
}


/**
 * 取得购物车总金额
 * @params  boolean $include_gift   是否包括赠品
 * @param   int     $type           类型：默认普通商品
 * @return  float   购物车总金额
 */
function cart_amount($include_gift = true, $type = CART_GENERAL_GOODS){
	
	$CommonModel	=	new CommonModel();
	
    $sql 			= 	"SELECT SUM(goods_price * goods_number) " .
		          	  	" FROM " . 'ybr_cart' .
			            " WHERE session_id = '" . SESS_ID . "' " .
			            "AND rec_type = '$type' ";
    if (!$include_gift){
        $sql .= ' AND is_gift = 0 AND goods_id > 0';
    }
    return floatval( $CommonModel->getOne($sql) );
}


/**
 * 发红包：发货时发红包
 * @param   int     $order_id   订单号
 * @return  bool
 */
function send_order_bonus($order_id){
    /* 取得订单应该发放的红包 */
    $bonus_list 		= 	order_bonus($order_id);
    $CommonModel		=	new CommonModel();

    /* 如果有红包，统计并发送 */
    if ($bonus_list){
        /* 用户信息 */
        $sql 			= 	"SELECT u.user_id, u.user_name, u.email " .
                			"FROM " . 'ybr_order_info' . " AS o, " .
                          	'ybr_users' . " AS u " .
			                "WHERE o.order_id = '$order_id' " .
			                "AND o.user_id = u.user_id ";
        $user 			= 	$CommonModel->getRow($sql);

        /* 统计 */
        $count 			= 	0;
        $money 			= 	'';
        foreach ($bonus_list AS $bonus){
            $count 		+= 	$bonus['number'];
            $money 		.= 	price_format($bonus['type_money']) . ' [' . $bonus['number'] . '], ';

            /* 修改用户红包 */
            $sql 		= 	"INSERT INTO " . 'ybr_user_bonus' . " (bonus_type_id, user_id) " .
                    		"VALUES('$bonus[type_id]', '$user[user_id]')";
            for ($i = 0; $i < $bonus['number']; $i++){
                if (!$CommonModel->query($sql)){
                    return $CommonModel->getError();
                }
            }
        }

        /* 如果有红包，发送邮件 
        if ($count > 0){
            $tpl = get_mail_template('send_bonus');
            $GLOBALS['smarty']->assign('user_name', $user['user_name']);
            $GLOBALS['smarty']->assign('count', $count);
            $GLOBALS['smarty']->assign('money', $money);
            $GLOBALS['smarty']->assign('shop_name', $GLOBALS['_CFG']['shop_name']);
            $GLOBALS['smarty']->assign('send_date', local_date($GLOBALS['_CFG']['date_format']));
            $GLOBALS['smarty']->assign('sent_date', local_date($GLOBALS['_CFG']['date_format']));
            $content = $GLOBALS['smarty']->fetch('str:' . $tpl['template_content']);
            send_mail($user['user_name'], $user['email'], $tpl['template_subject'], $content, $tpl['is_html']);
        }*/
    }

    return true;
}

/**
 * 获取地区的名字
 * 
 */
function get_region_name($region_id){	
	$RegionModel	=	M('Region');	
	return $RegionModel->where(" region_id = '{$region_id}' ")->getField('region_name');
}

/**
 * 更新购物车中的商品数量
 *
 * @access  public
 * @param   array   $arr
 * @return  void
 */
function flow_update_cart($arr){
	
	$CommonModel	=	new CommonModel();
	
    /*处理*/
    foreach ($arr AS $key => $val){
        $val 		= 	intval(make_semiangle($val));
        if ($val <= 0 && !is_numeric($key)){
            continue;
        }

        /*查询*/
        $sql 		= 	"SELECT `goods_id`, `goods_attr_id`, `product_id`, `extension_code` FROM " . ' ybr_cart' .
               			" WHERE rec_id='$key' AND session_id='" . SESS_ID . "'";
        $goods 		= 	$CommonModel->getRow($sql);
		
        $sql 		= 	"SELECT g.goods_name, g.goods_number ".
                		"FROM " . ' ybr_goods ' . " AS g, ".
                    	'ybr_cart' . " AS c ".
                		"WHERE g.goods_id = c.goods_id AND c.rec_id = '$key'";
        $row 		= 	$CommonModel->getRow($sql);

        /*查询：系统启用了库存，检查输入的商品数量是否有效*/
        if (intval($GLOBALS['_CFG']['use_storage']) > 0 && $goods['extension_code'] != 'package_buy'){
            if ($row['goods_number'] < $val){
                //show_message(sprintf($GLOBALS['_LANG']['stock_insufficiency'], $row['goods_name'],$row['goods_number'], $row['goods_number']));
                $GLOBALS['err']->add($GLOBALS['_LANG']['stock_insufficiency'] . $row['goods_name'], $row['goods_number']); /*1：商品数量库存不足*/
                //exit;
            }
            /*是货品*/
            $goods['product_id'] 	= 	trim($goods['product_id']);
            if (!empty($goods['product_id'])){
                $sql 				= 	"SELECT product_number FROM " . 'ybr_products' . " WHERE goods_id = '" 
                						. $goods['goods_id'] . "' AND product_id = '" . $goods['product_id'] . "'";

                $product_number 	= 	$CommonModel->getOne($sql);
                if ($product_number < $val){
                    //show_message(sprintf($GLOBALS['_LANG']['stock_insufficiency'], $row['goods_name'],$product_number['product_number'], $product_number['product_number']));
                    $GLOBALS['err']->add($GLOBALS['_LANG']['stock_insufficiency'] . $row['goods_name'], $product_number['product_number']);/*2：货品数量库存不足*/
                    //exit;
                }
            }
        }
        elseif (intval($GLOBALS['_CFG']['use_storage']) > 0 && $goods['extension_code'] == 'package_buy'){
            if (judge_package_stock($goods['goods_id'], $val)){
                //show_message($GLOBALS['_LANG']['package_stock_insufficiency']);
                $GLOBALS['err']->add($GLOBALS['_LANG']['package_stock_insufficiency'], 0); /*3：团购商品数量库存不足*/
                //exit;
            }
        }

        /* 查询：检查该项是否为基本件 以及是否存在配件 */
        /* 此处配件是指添加商品时附加的并且是设置了优惠价格的配件 此类配件都有parent_id goods_number为1 */
        $sql = "SELECT b.goods_number, b.rec_id
                FROM " . 'ybr_cart' . " a, " . 'ybr_cart' . " b
                WHERE a.rec_id = '$key'
                AND a.session_id = '" . SESS_ID . "'
                AND a.extension_code <> 'package_buy'
                AND b.parent_id = a.goods_id
                AND b.session_id = '" . SESS_ID . "'";

        $offers_accessories_res 	= 	M()->query($sql);
		        
        /*订货数量大于0*/
        if ($val > 0){
            /* 判断是否为超出数量的优惠价格的配件 删除*/
            $row_num 				= 	1;
            foreach($offers_accessories_res as $offers_accessories_row){
            	if ($row_num > $val){
                    $sql 			= 	"DELETE FROM " . 'ybr_cart' .
			                            " WHERE session_id = '" . SESS_ID . "' " .
			                            "AND rec_id = '" . $offers_accessories_row['rec_id'] ."' LIMIT 1";
                    M()->execute($sql);
                }
                $row_num ++;
            }
            
            /*处理超值礼包 */
            if ($goods['extension_code'] == 'package_buy'){
                /*更新购物车中的商品数量*/
                $sql 				= 	"UPDATE " . ' ybr_cart ' .
                        				" SET goods_number = '$val' WHERE rec_id='$key' AND session_id='" . SESS_ID . "'";
            }
            /* 处理普通商品或非优惠的配件 */
            else{
                $attr_id    		= 	empty($goods['goods_attr_id']) ? array() : explode(',', $goods['goods_attr_id']);
                $goods_price 		= 	get_final_price($goods['goods_id'], $val, true, $attr_id);

                /*更新购物车中的商品数量*/
                $sql 				= 	"UPDATE " . ' ybr_cart ' .
                        				" SET goods_number = '$val', goods_price = '$goods_price' WHERE rec_id='$key' AND session_id='" . SESS_ID . "'";
            }
        }
        /*订货数量等于0*/
        else{
            /* 如果是基本件并且有优惠价格的配件则删除优惠价格的配件 */
        	foreach($offers_accessories_res as $offers_accessories_row){
        		$sql 				= 	"DELETE FROM " . ' ybr_cart ' .
                        				" WHERE session_id = '" . SESS_ID . "' " .
                        				"AND rec_id = '" . $offers_accessories_row['rec_id'] ."' LIMIT 1";
                M()->execute($sql);
        	}
        	
            $sql 					= 	"DELETE FROM " . 'ybr_cart' .
                						" WHERE rec_id='$key' AND session_id='" .SESS_ID. "'";
        }
        M()->query($sql);
    }
    /* 删除所有赠品 */
    $sql 							= 	"DELETE FROM " . 'ybr_cart' . " WHERE session_id = '" .SESS_ID. "' AND is_gift <> 0";
    M()->execute($sql);
}

/**
 * 检查购物车的详细信息
 * 
 */
function check_cart(){
	$CommonModel		=	new CommonModel();
	/* 循环、统计 */
    $sql 				= 	"SELECT *, IF(parent_id, parent_id, goods_id) AS pid " .
				            " FROM " . 'ybr_cart' . " " .
				            " WHERE session_id = '" . SESS_ID . "' AND rec_type = '" . CART_GENERAL_GOODS . "'" .
				            " ORDER BY pid, parent_id";
    $res 				= 	$CommonModel->query($sql);
	
    $goods_amount		=	0;
    foreach($res as $row){
    	$goods_amount	+=	$row['goods_number'];
    }    
    $datas['goods_list']	=	$res;
    $datas['goods_amount']	=	$goods_amount;
	return $datas;
}











